namespace Billing
{
    using AjaxControlToolkit;
    using System;
    using System.Data;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using Microsoft.Security.Application;

    public class ucUserProfile : UserControl
    {
        protected UpdatePanel ActionPanel;
        protected Button btnDelete;
        protected ConfirmButtonExtender btnDelete_ConfirmButtonExtender;
        protected Button btnReset;
        protected Button btnSave;
        protected DropDownList ddlAgency;
        protected DropDownList ddlBU;
        protected DropDownList ddlUserType;
        private DataTable dt;
        protected Panel PanelDetails;
        protected Panel PanelKeyManager;
        protected RadioButtonList RListIsActive;
        protected Timer TimerCloseIt;
        protected TextBox txtAddress01;
        protected TextBox txtAddress02;
        protected TextBox txtDisplayName;
        protected TextBox txtEmail;
        protected TextBox txtFaxNumber;
        protected TextBox txtLoginId;
        protected TextBox txtNRIC;
        protected TextBox txtPostCode;
        protected TextBox txtPrimaryPhone;
        protected TextBox txtSecondaryPhone;
        protected ucHighlight ucHighlight1;
        protected UpdatePanel UpdatePanel1;
        protected UpdatePanel updatePanel3;
        protected UpdateProgress UpdateProgress2;
        protected HiddenField xDialogID;
        protected HiddenField xIsOnlyKM;
        protected HiddenField xPassword;
        protected HiddenField xPrimaryKey;

        private void BindDLLAgency()
        {
            DataTable dt = new ClsAgency().SelectAll();
            this.ddlAgency.Items.Clear();
            this.ddlAgency.Items.Add(new ListItem("Select Agency", "0"));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                this.ddlAgency.Items.Add(new ListItem(Encoder.HtmlEncode(dt.Rows[i]["AgencyIDName"].ToString()), Encoder.HtmlEncode(dt.Rows[i]["ID"].ToString())));
            }
            this.ddlAgency.DataBind();
            this.BindDLLBUsInAgency();
        }

        private void BindDLLBUsInAgency()
        {
            ClsBUsInAgency cls = new ClsBUsInAgency();
            if (this.ddlAgency.SelectedIndex <= 0)
            {
                cls.AgencyID = 0;
            }
            else
            {
                cls.AgencyID = Convert.ToInt64(this.ddlAgency.SelectedValue);
            }
            DataTable dt = cls.SelectByAgencyID();
            this.ddlBU.Items.Clear();
            this.ddlBU.Items.Add(new ListItem("Select BU", "0"));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                this.ddlBU.Items.Add(new ListItem(Encoder.HtmlEncode(dt.Rows[i]["BUIDName"].ToString()), Encoder.HtmlEncode(dt.Rows[i]["ID"].ToString())));
            }
        }

        private void BindDLLUserType()
        {
            DataTable dt = new ClsGroupMember().SelectAll();
            this.ddlUserType.Items.Clear();
            this.ddlUserType.Items.Add(new ListItem("Select User Group", "0"));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (this.IsOnlyKM)
                {
                    if (dt.Rows[i]["GroupName"].ToString().ToLower().StartsWith("key"))
                    {
                        this.ddlUserType.Items.Add(new ListItem(Encoder.HtmlEncode(dt.Rows[i]["GroupName"].ToString()), Encoder.HtmlEncode(dt.Rows[i]["GroupID"].ToString())));
                    }
                }
                else
                {
                    this.ddlUserType.Items.Add(new ListItem(Encoder.HtmlEncode(dt.Rows[i]["GroupName"].ToString()), Encoder.HtmlEncode(dt.Rows[i]["GroupID"].ToString())));
                }
            }
        }

        private void BindEditData()
        {
            if ((this.dt != null) && (this.dt.Rows.Count > 0))
            {
                this.txtLoginId.Text = this.dt.Rows[0]["LoginId"].ToString();
                this.txtNRIC.Text = ClsPasswordHelper.Decrypt(this.dt.Rows[0]["NRIC"].ToString());
                this.ViewState["LoginID"] = this.txtLoginId.Text;
                this.txtDisplayName.Text = this.dt.Rows[0]["Name0"].ToString();
                this.txtAddress01.Text = this.dt.Rows[0]["Address01"].ToString();
                this.txtAddress02.Text = this.dt.Rows[0]["Address02"].ToString();
                this.txtPostCode.Text = this.dt.Rows[0]["PostCode"].ToString();
                this.txtPrimaryPhone.Text = this.dt.Rows[0]["PrimaryPhone"].ToString();
                this.txtSecondaryPhone.Text = this.dt.Rows[0]["SecondaryPhone"].ToString();
                this.txtFaxNumber.Text = this.dt.Rows[0]["FaxNumber"].ToString();
                this.txtEmail.Text = this.dt.Rows[0]["Email"].ToString();
                this.xPassword.Value = ClsPasswordHelper.Decrypt(this.dt.Rows[0]["LoginPassword"].ToString());
                this.xPrimaryKey.Value = this.dt.Rows[0]["UserID"].ToString();
                this.ddlUserType.SelectedIndex = -1;
                try
                {
                    if (this.dt.Rows[0]["UserTypeID"].ToString() != "0")
                    {
                        this.ddlUserType.Items.FindByValue(this.dt.Rows[0]["UserTypeID"].ToString()).Selected = true;
                    }
                    this.ddlAgency.SelectedIndex = -1;
                    if (this.dt.Rows[0]["AgencyID"].ToString() != "0")
                    {
                        this.ddlAgency.Items.FindByValue(this.dt.Rows[0]["AgencyID"].ToString()).Selected = true;
                    }
                    this.BindDLLBUsInAgency();
                    this.ddlBU.SelectedIndex = -1;
                    if (this.dt.Rows[0]["BUID"].ToString() != "0")
                    {
                        this.ddlBU.Items.FindByValue(this.dt.Rows[0]["BUID"].ToString()).Selected = true;
                    }
                    if (this.ddlAgency.SelectedIndex > 0)
                    {
                        this.PanelKeyManager.Visible = true;
                    }
                    else
                    {
                        this.PanelKeyManager.Visible = false;
                    }
                }
                catch (Exception ex)
                {
                    log4net.Logger.Error("Exception:\r\n Type:" + ex.GetType() + ";\r\n Message:" + ex.Message + ";\r\n Trace:" + ex.StackTrace);
                }
                this.RListIsActive.SelectedIndex = -1;
                this.RListIsActive.Items.FindByValue(this.dt.Rows[0]["UserStatus"].ToString()).Selected = true;
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            ClsUserProfile cls = new ClsUserProfile();
            if (Convert.ToInt64(this.xPrimaryKey.Value) > 0)
            {
                cls.ID = Convert.ToInt64(this.xPrimaryKey.Value);
                cls.Delete();
                this.ucHighlight1.Message = "Record Deleted";
            }
            ClsUtilityHelper.ResetFormControlValues(this);
            this.TimerCloseIt.Enabled = true;
        }

        protected void btnReset_Click(object sender, EventArgs e)
        {
            ClsUtilityHelper.ResetFormControlValues(this);
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (this.txtLoginId.Text.Trim() == "")
            {
                this.ucHighlight1.ErrorMessage = "Invalid Login Name";
            }
            else if ((this.txtNRIC.Text.Trim() != "") && !ClsNRICHelper.CheckNRIC(this.txtNRIC.Text.Trim()))
            {
                this.ucHighlight1.ErrorMessage = "Invalid NRIC";
            }
            else if (this.txtEmail.Text == "")
            {
                this.ucHighlight1.ErrorMessage = "Email required";
            }
            else if (this.txtDisplayName.Text == "")
            {
                this.ucHighlight1.ErrorMessage = "Display Name required";
            }
            else
            {
                bool flag = ClsValidationHelper.IsRecordExist("UserProfile", "LoginID", this.txtLoginId.Text);
                if (flag && Convert.ToInt64(this.xPrimaryKey.Value) == 0)
                {
                    this.ucHighlight1.ErrorMessage = " Record Exists. ";
                }
                else if ((flag && Convert.ToInt64(this.xPrimaryKey.Value) > 0) && (this.ViewState["LoginID"].ToString().ToUpper() != this.txtLoginId.Text.ToUpper()))
                {
                    this.ucHighlight1.ErrorMessage = " Record Exists. ";
                }
                else
                {
                    ClsUserProfile cls = new ClsUserProfile {
                        LoginId = this.txtLoginId.Text,
                        Name0 = this.txtDisplayName.Text,
                        NRIC = ClsPasswordHelper.Encrypt(this.txtNRIC.Text),
//                        this.txtDisplayName.Text,
                        Address01 = this.txtAddress01.Text,
                        Address02 = this.txtAddress02.Text,
                        PostCode = this.txtPostCode.Text,
                        PrimaryPhone = this.txtPrimaryPhone.Text,
                        SecondaryPhone = this.txtSecondaryPhone.Text,
                        FaxNumber = this.txtFaxNumber.Text,
                        Email = this.txtEmail.Text
                    };
                    if (this.ddlUserType.SelectedIndex <= 0)
                    {
                        this.ucHighlight1.ErrorMessage = "Please Select User Group";
                    }
                    else
                    {
                        if (this.ddlUserType.SelectedIndex != -1)
                        {
                            cls.UserTypeId = Convert.ToInt64(this.ddlUserType.SelectedValue);
                        }
                        else
                        {
                            cls.UserTypeId = 0;
                        }
                        if (this.ddlUserType.SelectedItem.Text.ToLower().Contains("key") || this.ddlUserType.SelectedItem.Text.ToLower().Contains("others"))
                        {
                            if (this.ddlAgency.SelectedIndex <= 0)
                            {
                                this.ucHighlight1.ErrorMessage = "Please Select Agency";
                                return;
                            }
                            if (this.ddlBU.SelectedIndex <= 0)
                            {
                                this.ucHighlight1.ErrorMessage = "Please Select BU";
                                return;
                            }
                            if (this.ddlAgency.SelectedIndex != -1)
                            {
                                cls.AgencyID = Convert.ToInt64(this.ddlAgency.SelectedValue);
                            }
                            else
                            {
                                cls.AgencyID = 0;
                            }
                            if (this.ddlBU.SelectedIndex != -1)
                            {
                                cls.BUID = Convert.ToInt64(this.ddlBU.SelectedValue);
                            }
                            else
                            {
                                cls.BUID = 0;
                            }
                        }
                        cls.UserStatus = Convert.ToBoolean(this.RListIsActive.SelectedValue);
                        if (Convert.ToInt64(this.xPrimaryKey.Value) > 0)
                        {
                            cls.ID = Convert.ToInt64(this.xPrimaryKey.Value);
                            cls.LoginPassword = ClsPasswordHelper.Encrypt(this.xPassword.Value);
                            cls.ModifiedBy = (long) base.Session["UserID"];
                            cls.Update();
                            this.ucHighlight1.Message = " Record Updated ";
                        }
                        else
                        {
                            cls.LoginPassword = ClsPasswordHelper.Encrypt(ClsPasswordHelper.Generate(8, 2, 1));
                            cls.CreatedBy = (long) base.Session["UserID"];
                            cls.Save();
                            cls.UpdateByLoginIdForPassword();
                            ClsEmailHelper clsEmail = new ClsEmailHelper();
                            ClsEmailTemplate clsTemplate = new ClsEmailTemplate();
                            clsEmail.IsBodyHtml = true;
                            clsTemplate.NewProfilePassword(cls.LoginId, ClsPasswordHelper.Decrypt(cls.LoginPassword));
                            clsEmail.MailToAdd(cls.Email);
                            clsEmail.Subject = clsTemplate.Subject;
                            clsEmail.Body0 = clsTemplate.Body0;
                            string Msg = clsEmail.SendEmail();
                            if (Msg.ToLower().Contains("fail"))
                            {
                                this.ucHighlight1.ErrorMessage = Msg;
                            }
                            this.ucHighlight1.Message = " Record Saved. " + Msg;
                        }
                        ClsUtilityHelper.ResetFormControlValues(this);
                        this.TimerCloseIt.Enabled = true;
                    }
                }
            }
        }

        public void Clear()
        {
            ClsUtilityHelper.ResetFormControlValues(this);
        }

        protected void ddlAgency_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.ddlAgency.SelectedIndex != -1)
            {
                this.BindDLLBUsInAgency();
            }
        }

        protected void ddlUserType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.ddlUserType.SelectedIndex != -1)
            {
                if (this.ddlUserType.SelectedItem.Text.ToLower().Contains("key") || this.ddlUserType.SelectedItem.Text.ToLower().Contains("others"))
                {
                    this.PanelKeyManager.Visible = true;
                }
                else
                {
                    this.PanelKeyManager.Visible = false;
                }
            }
        }

        protected void Page_Init(object sender, EventArgs e)
        {
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.Page.IsPostBack)
            {
                this.BindDLLUserType();
                this.BindDLLAgency();
                this.BindDLLBUsInAgency();
                this.BindEditData();
            }
            this.ucHighlight1.CloseAll();
        }

        protected void TimerCloseIt_Tick(object sender, EventArgs e)
        {
            ClsUtilityHelper.CloseJQueryDialog(this.DialogName, this);
            this.TimerCloseIt.Enabled = false;
            ClsUtilityHelper.EnableFormControlValues(this);
            this.ucHighlight1.CloseAll();
        }

        public bool Create0
        {
            get
            {
                return this.btnSave.Visible;
            }
            set
            {
                this.btnSave.Visible = value;
            }
        }

        public bool Delete0
        {
            get
            {
                return this.btnDelete.Visible;
            }
            set
            {
                this.btnDelete.Visible = value;
            }
        }

        public string DialogName
        {
            get
            {
                return this.xDialogID.Value;
            }
            set
            {
                this.xDialogID.Value = value;
            }
        }

        public DataTable EditData
        {
            get
            {
                return this.dt;
            }
            set
            {
                this.dt = value;
                this.BindEditData();
                this.TimerCloseIt.Enabled = false;
            }
        }

        public bool IsOnlyKM
        {
            get
            {
                return Convert.ToBoolean(this.xIsOnlyKM.Value);
            }
            set
            {
                this.xIsOnlyKM.Value = value.ToString();
            }
        }

        public bool Update0
        {
            get
            {
                return this.btnSave.Visible;
            }
            set
            {
                this.btnSave.Visible = value;
            }
        }
    }
}
